<?php

namespace Biz\service;

use Biz\cache\Goods as cGoods;
use Biz\cache\GoodsRecommend;
use Biz\cache\PhotoRelaBaseGoods as cPhotoRelaBaseGoods;
use Biz\cache\PhotoRelaGoodsIds as cPhotoRelaGoodsIds;
use Biz\cache\PicRelaGoodsIds as cPicRelaGoodsIds;
use Biz\model\activity\LimitTimeRobbingSku;
use Biz\model\GoodsBasicInfo;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\GoodsExtendInfo;
use Biz\model\GoodsSku;
use Biz\model\PhotoRelaGoods as mPhotoRelaGoods;
use Biz\model\ShopFavorite;
use Biz\model\ShopGoodsPool;
use Biz\module\Classes\wiki\SpuToWiki;
use Biz\module\Packages\CustomerService\SmallEnergy as csSmallEnergy;
use Biz\module\Packages\GoodsFormatInfo\Scene\Goods;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\activity\FullShipping as sFullShipping;
use Biz\service\Category as sCategory;
use Biz\service\Goods as serviceGoods;
use Biz\service\Goods as sGoods;
use Biz\service\GoodsHistory as sGoodsHistory;
use Biz\service\search\Brand;
use Biz\service\ShippingTempl as sShippingTempl;
use Biz\service\wiki\Wiki;
use Biz\tools\Amount;
use Doraemon\model\Category as mCategory;
use Doraemon\model\UserRelaGoods;
use Biz\service\brand\Brand as sBrand;
use Doraemon\service\Goods as DGoods;
use Doraemon\service\Photos;
use Doraemon\service\SearchAddTag;
use Doraemon\tools\HhzClient;
use Doraemon\tools\ImgUrl;
/**
 * @deprecated
 */
class GoodsDetail
{

    const PHOTO_RELA_GOODS_KEY = "category";

    const PHOTO_RELA_GOODS_MAX_COUNTER = 40;

    public static function GoodsDetail($goods_id, $areaCode = 0, $userId = 0)
    {
        if (!$goods_id) {
            throw new \Exception('goods_id 值为空');
        }
        $GoodsInfos = self::GoodsInfoList([$goods_id], $areaCode, [
            ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING,
        ], $userId);

        //商家相关客服信息
        $uid = array_column($GoodsInfos, 'uid');
        $smallEnergyInfo = csSmallEnergy::getSmallEnergyInfoByShopId($uid, ['pre_sale_reception_group_id']);
        $GoodsInfos[$goods_id]['small_energy'] = $smallEnergyInfo;

        $GoodsInfos = array_column($GoodsInfos, null, "goods_id");
        $GoodsDetail = $GoodsInfos[$goods_id];
        if (isset($GoodsDetail['active_top']) && $GoodsDetail['active_top']) {
            list($nocacheGoodsIDS, $active_top) = \Biz\cache\Activitys::getMultiRobbing([$goods_id]);
            if (!$active_top[$goods_id]['sku_list']) {
                $GoodsDetail['active_top'] = null;
            }
        }


        $wiki_id = $GoodsDetail['wiki_id'];

        $GoodsDetail = Goods::SpuDetail($GoodsDetail);
        $GoodsDetail['same_goods'] = null;
        $GoodsDetail['share_info'] = Share::getGoodsShare($GoodsDetail);

        if ($wiki_id) {
            $SameGoodsInfos = mGoodsBasicInfo::getInfos(['wiki_id' => $wiki_id, 'goods_id[!]' => $goods_id, 'status' => [mGoodsBasicInfo::STATUS_PASSED, mGoodsBasicInfo::STATUS_ONLINE]]);

            $SameGoodsid = array_column($SameGoodsInfos, 'goods_id');
            $SameGoods = self::GoodsInfoList($SameGoodsid, $areaCode, [
                ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING,
            ]);
            $GoodsDetail['same_goods'] = $SameGoods ? Goods::SameGoods($SameGoods) : null;
        }


        if ($userId > 0) {
            //追加浏览记录
            sGoodsHistory::addBrowseHistory($userId, $goods_id);
        }


        return $GoodsDetail;

    }


    public static function GoodsSharePage($goods_id)
    {

        $goodsDetail = self::GoodsDetail($goods_id);
        $skuInfo = self::SearchSku($goods_id, false);

        $goodsDetail['sku_info'] = $skuInfo;
        $goodsDetail['share_info'] = Share::getGoodsShare($goodsDetail);

        return $goodsDetail;
    }


    public static function SearchSku($goods_id, $withGoods = true)
    {
        $returnRlt = [
            'sku_attr' => [],
            'sku_info' => [],
        ];
        if ($withGoods) {

            $GoodsInfos = self::GoodsInfoList([$goods_id]);
            $GoodsInfos = array_column($GoodsInfos, null, "goods_id");
            $returnRlt['goods_info'] = [
                "min_price" => $GoodsInfos[$goods_id]['min_price'],
                "max_price" => $GoodsInfos[$goods_id]['max_price'],
                "cover_img" => $GoodsInfos[$goods_id]['spec_img_url'],
                "stock" => (int)$GoodsInfos[$goods_id]['stock'],
            ];
        }

        if (version_compare(HhzClient::getClientVersion(), '3.4.0', '>=')) {
            $returnRlt['goods_info'] = array_merge($returnRlt['goods_info'], [
                "active_top" => $GoodsInfos[$goods_id]['active_top'] && self::is_has_timerob_stock([$goods_id])[$goods_id] ? $GoodsInfos[$goods_id]['active_top'] : null
            ]);
        }

        $skuInfos = SkuInfo::getSkuList([$goods_id], [], false);

        $select_sign = true;
        foreach ($skuInfos as $skuInfo) {

            $returnRlt['sku_info'][] = [
                'sku_id' => $skuInfo['id'],
                'sku_params' => self::filterSkuAttrId($skuInfo['sku_attr_t1'], $skuInfo['sku_attr_t2']),
                'sku_desc' => $skuInfo['name'],
                'sell_price' => $skuInfo['price'],
                'buy_price' => $skuInfo['buy_price'],
                'is_selected' => ($select_sign && ($skuInfo['price'] > $skuInfo['buy_price'])) ? true : false,
                'promo_limit' => $skuInfo['promo_info'] ? $skuInfo['promo_info']['promo_limit'] : 0,
                'stock' => $skuInfo['stock']
            ];
            if ($skuInfo['price'] > $skuInfo['buy_price']) $select_sign = false;


            foreach ([1, 2] as $t) {

                if (isset($skuInfo['sku_attr_t' . $t]) && $skuInfo['sku_attr_t' . $t])
                    $returnRlt['sku_attr'][$skuInfo['sku_attr_t' . $t]['type']] = [
                        'type' => $skuInfo['sku_attr_t' . $t]['type'],
                        'tag' => $skuInfo['sku_attr_t' . $t]['tag'],
                        'title' => str_replace('尺寸', '尺码', $skuInfo['sku_attr_t' . $t]['title']),
                        'params' => isset($returnRlt['sku_attr'][$skuInfo['sku_attr_t' . $t]['type']]['params']) ? array_merge($returnRlt['sku_attr'][$skuInfo['sku_attr_t' . $t]['type']]['params'], [[
                            'id' => $skuInfo['sku_attr_t' . $t]['id'],
                            'tag' => $skuInfo['sku_attr_t' . $t]['tag'],
                            'value' => $skuInfo['sku_attr_t' . $t]['value'],
                            'extend_info' => $skuInfo['sku_attr_t' . $t]['extend_info'],
                            'extend_info_url' => $skuInfo['sku_attr_t' . $t]['extend_info_url'],
                            'extend_info_thumb_url' => $skuInfo['sku_attr_t' . $t]['extend_info_thumb_url'],
                        ]]) : [[
                            'id' => $skuInfo['sku_attr_t' . $t]['id'],
                            'tag' => $skuInfo['sku_attr_t' . $t]['tag'],
                            'value' => $skuInfo['sku_attr_t' . $t]['value'],
                            'extend_info' => $skuInfo['sku_attr_t' . $t]['extend_info'],
                            'extend_info_url' => $skuInfo['sku_attr_t' . $t]['extend_info_url'],
                            'extend_info_thumb_url' => $skuInfo['sku_attr_t' . $t]['extend_info_thumb_url'],
                        ]]
                    ];
            }
        }

        $returnRlt['sku_attr'] = array_values($returnRlt['sku_attr']);
        foreach ($returnRlt['sku_attr'] as &$sku_attr) {
            $sku_attr['params'] = array_values(array_column($sku_attr['params'], null, 'id'));
        }

        return $returnRlt;
    }

    private static function filterSkuAttrId($t1, $t2)
    {
        $rst = [];
        if ($t1) {
            $rst['t1'] = (int)$t1['id'];
        }
        if ($t2) {
            $rst['t2'] = (int)$t2['id'];
        }
        return $rst;
    }

    public static function GoodsInfoList($goodsIds, $areaCode = 0, $activity_types = [
        ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING,
        ActivityInfo::ACTIVITY_TYPE_ADDRESS_FREE,
        ActivityInfo::ACTIVITY_TYPE_NEW
    ], $userId = 0) //extends = basic  all
    {
        $goodsBasicInfos = self::formatBasicInfos($goodsIds);

//		$wiki_ids = array_column($goodsBasicInfos, 'wiki_id');
        $LimitTimeRobbings = Activitys::getLimitTimeRobbingByGids($goodsIds);
        $is_favs = $userId ? ShopFavorite::is_favorited($userId, $goodsIds, ShopFavorite::TYPE_GOODS) : [];

//		$wikiInfos = $wiki_ids ? Spu::getSpuListByIDs4App($wiki_ids, HhzClient::getUid()) : [];
//		$wikiInfos = array_column($wikiInfos, null, 'id');


        $goodsBasicInfos = array_map(function ($goodsBasicInfo) use ($LimitTimeRobbings, $is_favs) {
//			$goodsBasicInfo['wiki_info'] =  isset($wikiInfos[$goodsBasicInfo['wiki_id']]) ? $wikiInfos[$goodsBasicInfo['wiki_id']] : (object)[];
            $goodsBasicInfo['spec_img_url'] = ImgUrl::checkFmt($goodsBasicInfo['spec_img_url']);
            $goodsBasicInfo['spec_img_thumb_url'] = ImgUrl::checkFmt($goodsBasicInfo['spec_img_thumb_url']);
            $goodsBasicInfo['imgs'] = ImgUrl::checkFmt($goodsBasicInfo['imgs']);
            $goodsBasicInfo['images_content_hash'] = ImgUrl::checkFmt($goodsBasicInfo['images_content_hash']);
            if ($goodsBasicInfo['brand_info']) {
                $goodsBasicInfo['brand_info']['logo'] = ImgUrl::checkFmt($goodsBasicInfo['brand_info']['logo']);
                $goodsBasicInfo['brand_info']['thumb_logo'] = ImgUrl::checkFmt($goodsBasicInfo['brand_info']['thumb_logo']);
            }

            foreach ($goodsBasicInfo['goods_detail'] as &$goodsDetail) {
                $goodsDetail['img_url'] = ImgUrl::checkFmt($goodsDetail['img_url']);
            }

            $goodsBasicInfo['active_top'] = null;
            if (isset($LimitTimeRobbings[$goodsBasicInfo['goods_id']])) {
                $robbing_id = $LimitTimeRobbings[$goodsBasicInfo['goods_id']]['id'];
                $robInfo = LimitTimeRobbingSku::getInfosByRobID($robbing_id, true)[$robbing_id];
                $skuIdsInLimitRob = array_column($robInfo, 'sku_id');
                $skuInLimitRob = GoodsSku::getSkus(['goods_id' => $goodsBasicInfo['goods_id'], 'id[!]' => $skuIdsInLimitRob]);
                $goodsBasicInfo['active_top'] = $LimitTimeRobbings[$goodsBasicInfo['goods_id']];
                if ($skuInLimitRob
                    && ($LimitTimeRobbings[$goodsBasicInfo['goods_id']]['params']['begin_time'] < $LimitTimeRobbings[$goodsBasicInfo['goods_id']]['params']['sys_time'])
                    && ($LimitTimeRobbings[$goodsBasicInfo['goods_id']]['params']['end_time'] > $LimitTimeRobbings[$goodsBasicInfo['goods_id']]['params']['sys_time'])
                ) {
                    $skuNoInLimitRobPrice = array_column($skuInLimitRob, 'price');
                    array_push($skuNoInLimitRobPrice, $goodsBasicInfo['active_top']['params']['min_price']);
                    $goodsBasicInfo['active_top']['params']['min_price'] = min($skuNoInLimitRobPrice);
                    $goodsBasicInfo['active_top']['params']['max_price'] = max($skuNoInLimitRobPrice);
                }

//				$priceList = [$goodsBasicInfo['min_price'], $goodsBasicInfo['max_price'], $goodsBasicInfo['active_top']['params']['min_price']];
//                $goodsBasicInfo['min_price'] = self::formatPrice(min($priceList));
//                $goodsBasicInfo['max_price'] = self::formatPrice(max($priceList));
            }

            $goodsBasicInfo['is_fav'] = isset($is_favs[$goodsBasicInfo['goods_id']]) ? $is_favs[$goodsBasicInfo['goods_id']] : 0;

            return $goodsBasicInfo;
        }, $goodsBasicInfos);


        // 活动相关
        $shipping_templ_ids = [];
        $shopIdsArr = [];
        foreach ($goodsBasicInfos as $goods_id => $goodsBasicInfo) {
            $shipping_templ_ids[] = $goodsBasicInfo['shipping_info']['templ_id'];
            if ($goodsBasicInfo['shop_info'] && isset($goodsBasicInfo['shop_info']['shop_id'])) {
                $shop_ids[] = $goodsBasicInfo['shop_info']['shop_id'];
                $shopIdsArr[$goodsBasicInfo['shop_info']['shop_id']][] = $goods_id;
            }
        }
        $uid = HhzClient::getUid();
        $shippingPrice = sShippingTempl::getDefaultShippingPrice($shipping_templ_ids, $areaCode, $uid);

        $fullShippingFrees = [];
        $addressFreeActivitys = [];
        $newGoods = [];

        array_walk($activity_types, function ($v, $k) use (&$fullShippingFrees, &$addressFreeActivitys, &$newGoods, $areaCode, $shopIdsArr, $shipping_templ_ids, $goodsIds) {
            switch ($v) {
                case ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING :
                    $fullShippingFrees = sFullShipping::quickGetFormatInfos($shopIdsArr, $areaCode);
                    break;
                case ActivityInfo::ACTIVITY_TYPE_ADDRESS_FREE :
                    $addressFreeActivitys = Activitys::AddressFree($shipping_templ_ids, $areaCode);
                    break;
                case ActivityInfo::ACTIVITY_TYPE_NEW :
                    $newGoods = Activitys::NewGoods($goodsIds);
            }
        });


        $goodsBasicInfos = array_map(function ($goodsBasicInfo) use ($fullShippingFrees, $addressFreeActivitys, $newGoods, $activity_types, $shippingPrice) {
            if (!isset($goodsBasicInfo['active_list'])) {
                $goodsBasicInfo['active_list'] = [];
            }

            if ($goodsBasicInfo['shop_info'] && isset($goodsBasicInfo['shop_info']['shop_id']) && isset($fullShippingFrees[$goodsBasicInfo['shop_info']['shop_id']][$goodsBasicInfo['goods_id']]) && $fullShippingFrees[$goodsBasicInfo['shop_info']['shop_id']][$goodsBasicInfo['goods_id']]) {
                array_push($goodsBasicInfo['active_list'], $fullShippingFrees[$goodsBasicInfo['shop_info']['shop_id']][$goodsBasicInfo['goods_id']]);
            }


            if (isset($newGoods[$goodsBasicInfo['goods_id']]) && $newGoods[$goodsBasicInfo['goods_id']]) {
                array_push($goodsBasicInfo['active_list'], $newGoods[$goodsBasicInfo['goods_id']]);
            }


            if (isset($addressFreeActivitys[$goodsBasicInfo['shipping_info']['templ_id']]) && $addressFreeActivitys[$goodsBasicInfo['shipping_info']['templ_id']]) {

                array_push($goodsBasicInfo['active_list'], $addressFreeActivitys[$goodsBasicInfo['shipping_info']['templ_id']]);

            }


            $goodsBasicInfo['shipping_info']['price'] = isset($shippingPrice[$goodsBasicInfo['shipping_info']['templ_id']]) && $shippingPrice[$goodsBasicInfo['shipping_info']['templ_id']] ? $shippingPrice[$goodsBasicInfo['shipping_info']['templ_id']] : "0.00";

            return $goodsBasicInfo;
        }, $goodsBasicInfos);


        return $goodsBasicInfos;

    }

    private static function formatPrice($price)
    {
        $price = (float)$price;
        if (strpos($price, ".") === FALSE) {
            return $price;
        }

        return Amount::format($price);

    }

    public static function formatBasicInfos($goodsIds)
    {

        list($cacheData, $goodsIds) = cGoods::getMultiGoods((array)$goodsIds);

        foreach ($cacheData as $goods_id => $goodsInfo) {
            isset($goodsInfo['style_content_desc']) ? null : array_push($goodsIds, $goods_id);
            isset($goodsInfo['first_online_time']) ? null : array_push($goodsIds, $goods_id);
            isset($goodsInfo['tags_content']) ? null : array_push($goodsIds, $goods_id);
        }

        if (!$goodsIds) {
            return $cacheData;
        }

        $goodsBasicInfos = mGoodsBasicInfo::getInfoList($goodsIds);

        $skus = SkuInfo::getSkuList((array)$goodsIds, [], false);
        $skuInfos = [];
        foreach ($skus as $sku) {
            $skuInfos[$sku['goods_id']][] = $sku;
        }
        $category_ids = array_merge(array_column($goodsBasicInfos, "category_id"), array_column($goodsBasicInfos, "second_category_id"), array_column($goodsBasicInfos, "third_category_id"), array_column($goodsBasicInfos, "four_category_id"));
        $categoryList = mCategory::selectCategorys($category_ids);
        $brand_ids = array_column($goodsBasicInfos, 'brand_id');
        $uids = array_column($goodsBasicInfos, 'uid');
        $brandInfos = sBrand::getBrandListByIds4App($brand_ids);
        $shopInfos = ShopInfo::getShopInfoList($uids, 'app');
        $extendInfos = GoodsExtendInfo::getExtendInfosByGid($goodsIds);
        $GoodsPriceAndStock = Sku::SkuInfos($goodsIds, Sku::FIELDS_GROUP_BASE_WITH_STOCK);
        $goodsBasicInfos = array_map(function ($goodsBasicInfo) use ($categoryList, $brandInfos, $shopInfos, $skuInfos, $extendInfos, $GoodsPriceAndStock) {
            $goodsBasicInfo['id'] = $goodsBasicInfo['goods_id'];
//			if (isset($skuInfos[$goodsBasicInfo['goods_id']])) {
            $skuInfo = isset($skuInfos[$goodsBasicInfo['goods_id']]) ? $skuInfos[$goodsBasicInfo['goods_id']] : [];
            $goodsBasicInfo['extinfo'] = array_column($skuInfo, 'extinfo');
            $goodsBasicInfo['min_price'] = isset($GoodsPriceAndStock[$goodsBasicInfo['goods_id']]) ? self::formatPrice($GoodsPriceAndStock[$goodsBasicInfo['goods_id']]['min_price']) : 0.00;
            $goodsBasicInfo['max_price'] = isset($GoodsPriceAndStock[$goodsBasicInfo['goods_id']]) ? self::formatPrice($GoodsPriceAndStock[$goodsBasicInfo['goods_id']]['max_price']) : 0.00;
            $goodsBasicInfo['stock'] = array_sum(array_column($skuInfo, "stock"));
//			} else {
//				$goodsBasicInfo['status'] = mGoodsBasicInfo::STATUS_OFFLINE;
//				mGoodsBasicInfo::updateData(['status' => mGoodsBasicInfo::STATUS_OFFLINE], ['goods_id' => $goodsBasicInfo['goods_id']]);
//				cGoods::delGoods($goodsBasicInfo['goods_id']);
//				cGoodsBaseInfo::delItem($goodsBasicInfo['goods_id']);
//			}
            $goodsBasicInfo['app_status'] = mGoodsBasicInfo::$statusAppMap[$goodsBasicInfo['status']];

            $goodsBasicInfo['category'] = array_map(function ($category_id) use ($categoryList) {
                if ($category_id && isset($categoryList[$category_id])) {

                    return ['cate_id' => $categoryList[$category_id]['cate_id'], 'cate_name' => $categoryList[$category_id]['cate_name']];
                }

                return null;
            }, [
                $goodsBasicInfo['category_id'], $goodsBasicInfo['second_category_id'], $goodsBasicInfo['third_category_id'], $goodsBasicInfo['four_category_id']
            ]);

            $goodsBasicInfo['category'] = array_filter($goodsBasicInfo['category']);

            $spec_params = isset($skuInfo) ? array_column($skuInfo, 'spec_params') : [];


            $params = '';
            foreach ($spec_params as $spec_param) {
                if ($spec_param) array_walk($spec_param, function ($v, $k) use (&$params) {
                    $params .= $k ? ($k . " " . $v) : $v;
                    $params .= "\n";
                });

                $params .= "\n";
            }

            trim($params) && $extendInfos[$goodsBasicInfo['goods_id']]['material_content'] ? array_push($extendInfos[$goodsBasicInfo['goods_id']]['material_content'], [
                'title' => '尺寸',
                'content' => $params
            ]) : null;

            $goodsBasicInfo['spec_params'] = $extendInfos[$goodsBasicInfo['goods_id']]['material_content'];
            $goodsBasicInfo['style_content'] = $extendInfos[$goodsBasicInfo['goods_id']]['style_content'];
            $goodsBasicInfo['tags_content'] = $extendInfos[$goodsBasicInfo['goods_id']]['tags_content'];
            $goodsBasicInfo['style_content_desc'] = $extendInfos[$goodsBasicInfo['goods_id']]['style_content_desc'];
            $goodsBasicInfo['goods_detail'] = $extendInfos[$goodsBasicInfo['goods_id']]['goods_detail'];
            $goodsBasicInfo['shipping_info'] = $extendInfos[$goodsBasicInfo['goods_id']]['shipping_info'];
            $goodsBasicInfo['imgs'] = array_column($extendInfos[$goodsBasicInfo['goods_id']]['images_content'], "url");
            $goodsBasicInfo['images_content_hash'] = array_column($extendInfos[$goodsBasicInfo['goods_id']]['images_content'], 'hash');
            $goodsBasicInfo['shop_info'] = isset($shopInfos[$goodsBasicInfo['uid']]) ? $shopInfos[$goodsBasicInfo['uid']] : (object)[];
            $goodsBasicInfo['brand_info'] = isset($brandInfos[$goodsBasicInfo['brand_id']]) && $brandInfos[$goodsBasicInfo['brand_id']] ? $brandInfos[$goodsBasicInfo['brand_id']] : null;
            return $goodsBasicInfo;
        }, $goodsBasicInfos);

        $res = cGoods::setMultiGoods($goodsBasicInfos);

        //		return $goodsBasicInfos;
        return array_column(array_merge($goodsBasicInfos, $cacheData), null, 'goods_id');

    }

    /**
     * 获取商品满包邮的活动列表
     * @param $goodsId 商品id
     * @return array
     * @throws \Exception
     */
    public static function FullShippingList($goodsId)
    {
        $goodsInfo = serviceGoods::goods([$goodsId], serviceGoods::FIELDS_GROUP_DETAIL);
        $shopId = $goodsInfo[$goodsId]['shop_info']['shop_id'];
        $FullShippingList = sFullShipping::FullShippingList($shopId, $goodsId);
        return isset($FullShippingList[$shopId]) ? $FullShippingList[$shopId] : [];
    }

    /*
     * 检测商品是否存在
     * **/
    public static function checkGoodsById($spuId)
    {

        $goodsInfo = mGoodsBasicInfo::checkGoodsById($spuId);
        if (!$goodsInfo) {
            return 0;
        } elseif ($goodsInfo['status'] != 2) {
            return 3;
        } else {
            return $goodsInfo;
        }
    }

    /**
     * @param $ClassifyId
     * @return array
     * @throws \Exception
     * 根据一级或者二级分类的ID 查找 分类下的categoryids
     */
    private static function getCateIdsByClassifyId($ClassifyId)
    {
        $subClassifyInfos = sCategory::getClassifyByid($ClassifyId);

        if (!isset($subClassifyInfos['cate_info']) && !isset($subClassifyInfos['sub_classifys'])) {
            throw new \Exception('不存在的二级分类ID');
        }

        $cateIds = [];
        if (isset($subClassifyInfos['sub_classifys'])) {
            $allClassifys = sCategory::getAllClassify($ClassifyId);
            foreach ($allClassifys[0]['second_classify_name'] as $secondClassify) {
                $cateIds = array_merge($cateIds, array_column($secondClassify['cate_infos'], 'id'));
            }
        } else {
            $cateIds = array_column($subClassifyInfos['cate_info'], 'id');
        }

        return ['classify_name' => $subClassifyInfos['classify_name'], 'cate_ids' => $cateIds];
    }

    public static function recommendGoods3_4($goodsId, $areaCode)
    {
        if (!$goodsId) {
            throw  new \Exception('GOODSID 为空');
        }
//        $goodsInfo = self::formatBasicInfos([$goodsId])[$goodsId];
        $goodsInfo = serviceGoods::goods($goodsId, serviceGoods::FIELDS_GROUP_BASE);

        $goodsIds = GoodsRecommend::getRecommendIds($goodsId);
        if (!$goodsIds) {
            $goodsIds = SearchGoods::recommendGoods($goodsId, $goodsInfo['shop_id'], $goodsInfo['category_id']);
            //  todo 搜索切换es待删除
//            $goodsIds = searchGoods::recommendGoods($goodsId, $goodsInfo['shop_id'], array_column($goodsInfo['category'], 'cate_id'));
            GoodsRecommend::setRecommendIds($goodsId, $goodsIds ?: [0]);
        }

        return array_filter($goodsIds) ?
            self::FormatBasicInfoOnGoodsInfoList($goodsIds, $areaCode)
            :
            [];
    }

    public static function FormatBasicInfoOnGoodsInfoList($goods_ids = [], $areaCode = 0)
    {

        $goodsList = serviceGoods::Goods($goods_ids, serviceGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode]);

        return array_values($goodsList);
    }

    private static function is_has_timerob_stock($goods_ids)
    {
        $Rst = [];
        list($nocacheGoodsIDS, $active_top) = \Biz\cache\Activitys::getMultiRobbing($goods_ids);

        foreach ($goods_ids as $goods_id) {
            if (isset($active_top[$goods_id])) {
                if ($active_top[$goods_id]['sku_list']) {
                    $Rst[$goods_id] = true;
                } else {
                    $Rst[$goods_id] = false;
                }
            } else {
                $Rst[$goods_id] = false;
            }
        }

        return $Rst;
    }

    public static function getGoodsInfoByPhotoId($photoId)
    {
        $goodsIds = mPhotoRelaGoods::getGoodsInfoByPhotoId($photoId, 'goods_id');
        $goodsInfos = self::GoodsInfoList($goodsIds);
        $goodsInfo = [];

        if ($goodsInfos) {
            $goodsInfo = array_map(function ($v) {

                $goodsInfo['id'] = $v['goods_id'];
                $goodsInfo['title'] = $v['title'];
                $goodsInfo['min_price'] = $v['active_top']['params']['min_price'] ?: $v['min_price'];
                $goodsInfo['max_price'] = $v['active_top']['params']['max_price'] ?: $v['max_price'];
                $goodsInfo['cover_img'] = $v['spec_img_url'];
                $goodsInfo['thumb_cover_img'] = $v['spec_img_thumb_url'];
                $goodsInfo['category_name'] = array_pop($v['category'])['cate_name'];
                $goodsInfo['brand_info'] = $v['brand_info'] ?: (object)[];
                return $goodsInfo;
            }, $goodsInfos);
        }

        $goodsInfo = array(
            'list' => array_values($goodsInfo),
            'count' => count($goodsInfo)
        );

        return $goodsInfo;
    }

    public static function getGoodsInfoByPhotoId3_10($noteId, $areaCode, $page, $pagesize = 20)
    {
        $resutl = [
            'note_id' => $noteId,
            'note_goods_list' => []
        ];
        $goodsIdsGrpByPicId = cPicRelaGoodsIds::getRelaGoodsIds($noteId);
        if (is_null($goodsIdsGrpByPicId)) {
            $goodsIdsGrpByPicId = self::relaGoodsIds($noteId, true);
            cPicRelaGoodsIds::setRelaGoodsIds($noteId, $goodsIdsGrpByPicId);
        }
        if ($page) {
            $offset = ($page - 1) * $pagesize;
        } else {
            $offset = 0;
            $pagesize = 8;
        }
        $basicRelaGoods = self::getBasicRelaGoods([$noteId])[$noteId];
        $list = [];
        foreach ($goodsIdsGrpByPicId as $picId => $goodsIds) {
            if (isset($basicRelaGoods[$picId])) {
                $basicRelaGoods[$picId] = array_filter($basicRelaGoods[$picId]);
                $basicRelaGoods[$picId] = array_column($basicRelaGoods[$picId], 'goods_id');
                $list = array_merge($list, array_values(serviceGoods::Goods(array_diff(array_slice($goodsIds, $offset, $pagesize), $basicRelaGoods[$picId]), serviceGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode])));
                $resutl['note_goods_list'][] = [
                    'pic_id' => $picId,
                    'list' => array_values(serviceGoods::Goods($basicRelaGoods[$picId], serviceGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode])),
                    'is_over' => count($goodsIds) >= (int)$page * $pagesize ? 0 : 1,
                    'count' => count($goodsIds)
                ];
            }
        }
        if ($resutl['note_goods_list']) $resutl['note_goods_list'][] = [
            'list' => $list,
            'is_over' => 1,
            'count' => count($list),
        ];
        return $resutl;
    }

    public static function getGoodsInfoByPhotoId_3_6($photoId, $provinceId, $version, $page = 0, $pagesize = 20)
    {
        $goodsIds = cPhotoRelaGoodsIds::getRelaGoodsIds($photoId);
        if ($goodsIds === false) {
            $goodsIds = self::relaGoodsIds($photoId);
            $goodsIds = array_unique($goodsIds);
            cPhotoRelaGoodsIds::setRelaGoodsIds($photoId, $goodsIds);
        }

        if ($page) {
            $offset = ($page - 1) * $pagesize;
        } else {
            $offset = 0;
            $pagesize = version_compare($version, "3.9.0", ">=") ? 4 : 3;
        }

        if (!$page) $Rst['count'] = count($goodsIds);
        $goodsIds = array_slice($goodsIds, $offset, $pagesize);
        $Rst['list'] = [];
        if ($goodsIds) {
            $goodsInfos = serviceGoods::Goods($goodsIds, serviceGoods::FIELDS_GROUP_LIST, ['area_code' => $provinceId], 0, array_keys(GoodsBasicInfo::$statusAppMap));
            $Rst['list'] = array_values($goodsInfos);
        }
        $Rst['is_over'] = count($goodsIds) < $pagesize ? 1 : 0;
        return $Rst;
    }

    public static function getGoodsCounterByPhotoIds($photoIds)
    {
        $results = [];
        $goodsList = self::getGoodsByPhotoIds($photoIds);
        foreach ($goodsList as $photoId => $goodsIds) {
            foreach ($goodsIds as $picId => $gids) {
                $results[$photoId][$picId] = count($gids) ? 1 : 0;
            }
        }
        return $results;
    }

    public static function getGoodsByPhotoIds($photoIds, $counter = 1, $isFormat = false)
    {
//		try {
//			list($cacheDatas, $noCacheData) = cPhotoRelaGoodsIds::pHGetAllItems($photoIds);
        list($cacheDatas, $noCacheData) = cPicRelaGoodsIds::pHGetAllItems($photoIds);
//		} catch (\Exception $e) {
//			//改过缓存字段类型
//			foreach ($photoIds as $photoId) {
//				cPhotoRelaGoodsIds::delItem($photoId);
//			}
//			list($cacheDatas, $noCacheData) = cPhotoRelaGoodsIds::pHGetAllItems($photoIds);
//		}
        $results = [];
        if ($noCacheData) {
            foreach ($noCacheData as $noCacheDatum) {
                $goodsIds = self::relaGoodsIds($noCacheDatum, true, $counter);
                $results[$noCacheDatum] = $goodsIds;
            }
        }

        foreach ($cacheDatas as $photoId => $cacheData) {
            $cacheData = array_filter($cacheData);
            foreach ($cacheData as $picId => $goodsIds) {
                $results[$photoId][$picId] = array_slice($goodsIds, 0, $counter);
            }
        }
        if ($isFormat) {
            foreach ($results as $photoId => $goodsIds) {
                foreach ($goodsIds as $picId => $gids) {
                    $results[$photoId][$picId] = serviceGoods::Goods($gids, serviceGoods::FIELDS_GROUP_LIST);
                }
            }
        }
        return $results;
    }

    private static function getBasicRelaGoods($noteIds)
    {
        list($cacheData, $noCacheData) = cPhotoRelaBaseGoods::pHGetAllItems($noteIds);
        $needCacheData = [];
        if ($noCacheData) {
            $PhotoRelaInfos = mPhotoRelaGoods::getGoodsInfoByPhotoId($noCacheData);
            foreach ($PhotoRelaInfos as $photoRelaInfo) {
                $needCacheData[$photoRelaInfo['obj_id']][$photoRelaInfo['rel_obj_id']][] = $photoRelaInfo;
            }
            foreach ($noCacheData as $noCachePhotoId) {
                if (!isset($needCacheData[$noCachePhotoId])) {
                    $needCacheData[$noCachePhotoId][] = 0;
                }
            }
            cPhotoRelaBaseGoods::pHMSetItems($needCacheData);
        }
        $PhotoRelaInfos = array_merge($cacheData, $needCacheData);
        return $PhotoRelaInfos;

    }

    //已弃用
    public static function isShowGoodsWindow($noteIds)
    {
        $PhotoRelaInfos = self::getBasicRelaGoods($noteIds);
        $results = [];
        foreach ($noteIds as $noteId) {
            $PhotoRelaInfos[$noteId] = array_filter($PhotoRelaInfos[$noteId]);
            if ($PhotoRelaInfos[$noteId]) {
                foreach ($PhotoRelaInfos as $noteId => $photoRelaInfo) {
                    foreach ($photoRelaInfo as $picId => $item) {
                        $results[$noteId][$picId] = $item ? 1 : 0;
                    }
                }
            } else {
                $results[$noteId] = [];
            }
        }

        return $results;
    }

    public static function relaGoodsIds($photoId, $isHasNote = false, $maxCounter = self::PHOTO_RELA_GOODS_MAX_COUNTER)
    {

        $relaInfos = mPhotoRelaGoods::getGoodsInfoByPhotoId($photoId, ['goods_id', 'rel_obj_id']);
        $goodsIds = [];
        if ($isHasNote) {
            $goodsIdsGrpByPic = [];
            foreach ($relaInfos as $relaInfo) {
                $goodsIdsGrpByPic[$relaInfo['rel_obj_id']][] = $relaInfo['goods_id'];
            }
            foreach ($goodsIdsGrpByPic as $picId => $GIds) {
                $goodsIds[$picId] = self::getRelaGooIds($GIds, $photoId, $isHasNote, $maxCounter, $picId);
            }
        } else {
            $goodsIds = self::getRelaGooIds(array_column($relaInfos, 'goods_id'), $photoId, $isHasNote, $maxCounter);
        }
        return $goodsIds;
    }

    private static function getRelaGooIds($goodsIds, $photoId, $isHasNote, $maxCounter, $picId = '')
    {
        $funs = [];
        if ($goodsIds) {
            $goodsBaseInfos = serviceGoods::Goods($goodsIds, serviceGoods::FIELDS_GROUP_BASE, ['area_code' => 0], 0, array_keys(mGoodsBasicInfo::$statusAppMap));
            $funs = [
                'getGoodsIdsByBrandAndCate',
                'getGoodsIdsByCate',
                'getGoodsIdsBySameLevelCate',
            ];
        }

        foreach ($funs as $fun) {
            if (count($goodsIds) < $maxCounter) {
                $tmpMaxCounter = $maxCounter - count($goodsIds);
                $goodsIds = call_user_func_array([self::class, $fun], [
                    $goodsIds,
                    $goodsBaseInfos,
                    $tmpMaxCounter
                ]);
            } else {
                break;
            }
        }
        if (count($goodsIds) < $maxCounter) {
            $tmpMaxCounter = $maxCounter - count($goodsIds);
            $goodsIds = self::getGoodsIdsByPhotoTag($goodsIds, $photoId, $isHasNote, $tmpMaxCounter, $picId);
        }


        return $goodsIds;

    }


    private static function getGoodsIdsByPhotoTag($goodsIds, $photoId, $isHasNote, $maxCounter, $picId)
    {
        $tags = self::getImgTags($photoId, $isHasNote, $picId);
        $goodsIds = self::getGoodsIdsByImgTags($goodsIds, $tags, $maxCounter);
        return $goodsIds;
    }

    private static function getGoodsIdsByImgTags($goodsIds, $imgTags, $maxCounter)
    {
        $result = Brand::searchByFields(['brand_alias' => $imgTags]);
        $brandIds = array_column($result['rows'], 'id');

        $goodsIds = array_merge($goodsIds,
            SearchGoods::searchGoodsIdsByCateNamesAndBrandIds($imgTags, $brandIds, $maxCounter, $goodsIds)
        );
        $maxCounter = $maxCounter - count($goodsIds);
        if ($maxCounter) {
            $goodsIds = array_merge($goodsIds,
                self::getGoodsIdsByImgSceneTags($imgTags, $brandIds, $maxCounter, $goodsIds)
            );
        }
        return $goodsIds;
    }

    private static function getGoodsIdsByImgSceneTags($imgTags, $brandIds, $maxCounter, $goodsIds)
    {
        $categoryNames = ShopCategoryEntrance::getCategoryBySceneTags($imgTags);
        return SearchGoods::searchGoodsIdsByCateNamesAndBrandIds($categoryNames, $brandIds, $maxCounter, $goodsIds);
//		return searchGoods::searchGoodsIdsByCateNamesAndBrandIds($categoryNames, $brandIds, $maxCounter, $goodsIds);
    }


    private static function getImgTags($photoId, $isHasNote, $picId)
    {
        if ($isHasNote) {
            $picInfo = Photos::getPicInfo($photoId, $picId);
            $tags = self::getGoodsOrBrandImgTags($picInfo['img_tags']);
        } else {
            $photoInfo = Photos::getPhoto($photoId);
            $tags = explode(',', $photoInfo['admin_tag']);
            $tags = array_merge($tags, array_column(Photos::showTag($photoInfo['remark']), 'title'));
            $tags = array_merge($tags, self::getGoodsOrBrandImgTags($photoInfo['img_tags']));
            $tags = array_filter($tags);
        }
        return $tags;
    }

    private static function getGoodsOrBrandImgTags($imgTags)
    {
        $tags = [];
        $imgTags = json_decode($imgTags, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($imgTags)) foreach ($imgTags as $imgTag) {
            if (isset($imgTag['type'])) {
                if ($imgTag['type'] == SearchAddTag::GOODS_TAG_TPYE) {
                    $tags[] = $imgTag['goods_info']['brand_name'] ? $imgTag['goods_info']['brand_name'] : $imgTag['goods_info']['category_name'];
                } else if ($imgTag['type'] == SearchAddTag::BRAND_TAG_TPYE) {
                    $tags[] = $imgTag['brand'];
                }
            }
        }
        return $tags;
    }

    private static function getGoodsIdsByBrandAndCate($goodsIds, $goodsBasicInfos, $maxCounter)
    {
        $brandIds = array_column($goodsBasicInfos, 'brand_id');
        $cateIds = array_column($goodsBasicInfos, 'last_category_id');
        if ($brandIds && $cateIds) {
            $goodsIds = array_merge($goodsIds,
                SearchGoods::searchGoodsIdsByBrandIdsAndCateIds($brandIds, $cateIds, $maxCounter, $goodsIds)
            // todo 搜索切换es待删除
//				searchGoods::searchGoodsIdsByBrandIdsAndCateIds($brandIds, $cateIds, $maxCounter, $goodsIds);
            );
        }
        return $goodsIds;
    }

    private static function getGoodsIdsByCate($goodsIds, $goodsBasicInfos, $maxCounter)
    {
        $cateIds = array_column($goodsBasicInfos, 'last_category_id');
        if ($cateIds) {
            $goodsIds = self::getGoodsIdsByCateIds($goodsIds, $cateIds, $maxCounter);
        }
        return $goodsIds;
    }

    private static function getGoodsIdsBySameLevelCate($goodsIds, $goodsBasicInfos, $maxCounter)
    {
        $cateIds = array_column($goodsBasicInfos, 'last_category_id');
        $cateIds = self::getSameLevelCate($cateIds);
        if ($cateIds) {
            $goodsIds = self::getGoodsIdsByCateIds($goodsIds, $cateIds, $maxCounter);
        }
        return $goodsIds;
    }

    private static function getSameLevelCate($cateIds)
    {
        $categoryInfos = mCategory::selectCategorys($cateIds);
        $cateIds = array_column($categoryInfos, 'father_id');
        return mCategory::getChildrenById($cateIds, 'id');
    }

    private static function getGoodsIdsByCateIds($goodsIds, $categoryIds, $maxCounter)
    {
//		$goodsIds = array_merge($goodsIds,
//			searchGoods::searchGoodsIdsByLastCateIds($categoryIds, $maxCounter, $goodsIds)
//		);

        return $goodsIds;
    }


    /**
     * @desc 商品收藏列表(入口)
     * @param $uid
     * @param $areaCode
     * @param $page
     * @param int $appSource
     * @return array
     */
    public static function GoodsFavoriteList($uid, $areaCode, $page, $appSource = 0)
    {
        $versionBool = version_compare(HhzClient::getClientVersion(), '3.19.0', '>=');
        $wikiVersionBool = version_compare(HhzClient::getClientVersion(), '3.20.0', '>=');
        if ($versionBool) {
            if ($wikiVersionBool) {
                $goodsFavList = self::wikiFavoriteListV20($uid, $areaCode, $appSource, $page);
            } else {
                $goodsFavList = self::wikiFavoriteList($uid, $areaCode, $appSource, $page);
            }
        } else {
            $goodsFavList = ShopFavorite::getFavInfos($uid, ShopFavorite::TYPE_GOODS, $appSource, $page);
            $goodsIds = array_column($goodsFavList['list'], 'obj_id');
            $goodsFavList['list'] = self::FormatBasicInfoOnGoodsInfoList($goodsIds, $areaCode);
        }

        if (!$appSource) $goodsFavList['is_has_nogoods_wiki'] = UserRelaGoods::is_has_nogoods_favlist($uid);
        return $goodsFavList;
    }

    /**
     * 3.20版本
     * @param $uid
     * @param $areaCode
     * @param $appSource
     * @param $page
     * @return array
     */
    public static function wikiFavoriteListV20($uid, $areaCode, $appSource, $page)
    {
        $rs = ShopFavorite::getFavInfos($uid, [ShopFavorite::TYPE_GOODS, ShopFavorite::TYPE_WIKI], $appSource, $page);
        $list = $rs['list'];
        $is_over = $rs['is_over'];
        $list = self::formatWikiFavoriteList($list, $areaCode, true);
        return compact('list', 'is_over');
    }

    public static function wikiFavoriteList($uid, $areaCode, $appSource, $page)
    {
        $rs = ShopFavorite::getFavInfos($uid, [ShopFavorite::TYPE_GOODS, ShopFavorite::TYPE_WIKI], $appSource, $page);
        $list = $rs['list'];
        $is_over = $rs['is_over'];
        $list = self::formatWikiFavoriteList($list, $areaCode);
        return compact('list', 'is_over');
    }

    /**
     * @param $list
     * @param int $areaCode
     * @param bool $changeWiki
     * @return array
     */
    public static function formatWikiFavoriteList($list, $areaCode = 0, $changeWiki = false)
    {
        $goods_ids = [];
        $wiki_ids = [];
        $all_wiki_ids = [];
        foreach ($list as $v) {
            switch ($v['obj_type']) {
                case ShopFavorite::TYPE_WIKI:
                    $wiki_ids[] = $v['obj_id'];
                    break;
                case ShopFavorite::TYPE_GOODS:
                    $goods_ids[] = $v['obj_id'];
                    break;
            }
        }

        //3.20版本之后,商家spu转换wiki
        $map = [];
        if ($changeWiki) {
            $map = $goods_ids ? SpuToWiki::getRelateWikiMapByGoodsIds($goods_ids) : [];
            $all_wiki_ids = array_merge($wiki_ids, array_values($map));
        }

        //获取商品列表,wiki列表
        $goodsList = empty($goods_ids) ? [] : serviceGoods::Goods($goods_ids, serviceGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode]);
        $wikiList = empty($all_wiki_ids) ? [] : Wiki::getWikiList($all_wiki_ids);

        $response = [];
        foreach ($list as $v) {
            $obj_id = $v['obj_id'];
            switch ($v['obj_type']) {
                case ShopFavorite::TYPE_WIKI:
                    if (isset($wikiList[$obj_id])) {
                        $temp = $wikiList[$obj_id];
                        $temp['is_fav'] = 1;
                        $response[] = $temp;
                    }
                    break;
                case ShopFavorite::TYPE_GOODS:
                    if (isset($map[$obj_id])) {//如果存在spu转换wiki
                        $different = !in_array($map[$obj_id], $wiki_ids);//排除已经存在的wiki
                        if (isset($wikiList[$map[$obj_id]]) && $different) {
                            $temp = $wikiList[$map[$obj_id]];
                            $temp['is_fav'] = 1;
                            $response[] = $temp;
                        }
                    } else {
                        if (isset($goodsList[$obj_id])) {
                            $temp = $goodsList[$obj_id];
                            $temp['is_fav'] = 1;
                            $temp['type'] = 0;
                            $response[] = $temp;
                        }
                    }
                    break;
            }
        }
        return $response;
    }


    public static function notSellFavList($uid, $page)
    {
        $wikiInfos = UserRelaGoods::getNoGoodsFavList($uid, $page);
        $wikiInfos['list'] = DGoods::batchGetGoodsInfo($wikiInfos['list'], $uid);

        return $wikiInfos;
    }

    public static function GoodsPoolList($poolId, $num = 10)
    {
        $poolInfo = ShopGoodsPool::getById($poolId);
        if (!$poolInfo) {
            throw new \Exception('商品池ID不存在');
        }
        $goodsIds = explode(',', $poolInfo['goods_ids']);
        shuffle($goodsIds);
        $goodsIds = array_slice($goodsIds, 0, $num);
        $goodsInfos = sGoods::Goods($goodsIds, sGoods::FIELDS_GROUP_LIST);

        return array_values($goodsInfos);
    }

    public static function PoolList()
    {
        return ShopGoodsPool::select(['id', 'title'], [
            'status' => ShopGoodsPool::STATUS_NORMAL,
            'ORDER' => ['create_time' => 'DESC']
        ]);
    }
}
